package com.ruoyi.purchase.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.purchase.domain.*;
import com.ruoyi.purchase.mapper.*;
import com.ruoyi.purchase.vo.*;
import com.ruoyi.system.domain.Vendors;
import com.ruoyi.system.domain.VendorsItems;
import com.ruoyi.system.mapper.ItemsMapper;
import com.ruoyi.system.mapper.VendorsItemsMapper;
import com.ruoyi.system.mapper.VendorsMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.purchase.service.IInspectionPlanService;

/**
 * 收料检验计划Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-31
 */
@Service
public class InspectionPlanServiceImpl implements IInspectionPlanService 
{
    @Autowired
    private InspectionPlanMapper inspectionPlanMapper;

    @Autowired
    private MaterialReceiveServiceImpl materialReceiveService;


    @Autowired
    private MaterialReceiveMapper materialReceiveMapper;

    @Autowired
    private BoxCodesMapper boxCodesMapper;

    @Autowired
    private VendorsMapper vendorsMapper;

    @Autowired
    private ItemsMapper itemsMapper;

    @Autowired
    private VendorsItemsMapper vendorsItemsMapper;

    @Autowired
    private RejectionRecordMapper rejectionRecordMapper;

    @Autowired
    private InspectionResultMapper inspectionResultMapper;


    @Autowired
    private InspectionSchemeMapper inspectionSchemeMapper;
    /**
     *
     * 获取计划id
     *
     * @param id 收料检验计划主键
     * @return 收料检验计划
     */
    @Override
    public String generatePlanId() {
        String dateStr = DateUtils.parseDateToStr("yyMMdd", new Date());
        String prefix = "IP" + dateStr;
        String maxPlanId = inspectionPlanMapper.selectMaxPlanId(prefix);
        int nextSeq=1;
        if (maxPlanId != null) {
            String sequence = maxPlanId.substring(8);
            nextSeq = Integer.parseInt(sequence) + 1;

        }
        return String.format("%s%03d", prefix, nextSeq);

    }





    @Override
    public AjaxResult createInspectionPlansFromReceive(String receiveId) {
        try {
        // 获取收料通知单详情
        MaterialReceiveVO materialReceiveVO=materialReceiveMapper.selectMaterialReceiveByreceiveId(receiveId);
        MaterialReceiveVO receiveVO = materialReceiveService.selectMaterialReceiveVOById(materialReceiveVO.getId());
        if (receiveVO == null) {
            return AjaxResult.error("未找到对应的收料通知单");
        }

        // 获取收料清单
        List<MaterialReceiveItemVO> receiveItems = receiveVO.getReceiveItems();
        if (receiveItems == null || receiveItems.isEmpty()) {
            return AjaxResult.error("收料通知单中没有收料清单");
        }

        List<InspectionPlan> plans = new ArrayList<>();

            String firstBoxCode = this.generatePlanId();
            String datePrefix = firstBoxCode.substring(0, 8);
            String sequenceStr = firstBoxCode.substring(8);
            int sequence = Integer.parseInt(sequenceStr);

        for (MaterialReceiveItemVO item : receiveItems) {
            // 检查是否已存在检验计划
            InspectionPlan existPlan = inspectionPlanMapper.selectByPoIdAndItemId(receiveVO.getPoId(), item.getItemId());
            if (existPlan != null) {
                continue; // 跳过已存在的检验计划
            }


            // 创建检验计划
            InspectionPlan plan = new InspectionPlan();

            int seq = ++sequence;
            plan.setPlanId(datePrefix + String.format("%05d", seq + 1));
            plan.setItemId(item.getItemId());
            plan.setReceiveId(receiveId);
            plan.setPoId(receiveVO.getPoId());
            plan.setItemId(item.getItemId());
            // 获取批次号（从箱码中获取）
            BoxCodesVO BoxCodes = boxCodesMapper.selectBoxCodesByPoIdAndItemId(receiveVO.getPoId(), item.getItemId());
            plan.setBatch(BoxCodes.getBatch());

            // 获取供应商信息
            VendorsItems vendorId = vendorsItemsMapper.selectVendorsByitemId(item.getItemId());
            Vendors vendors = vendorsMapper.selectVendorsByVendorId(vendorId.getVendorId());
            plan.setVendorId(vendors.getVendorId());

            plan.setInspectionStatus(0); // 待检验
            plan.setActualQuantity(item.getCurrentReceiveQuantity());
            plan.setActualQuantity(0L);
            plan.setQualifiedQuantity(0L);
            plan.setInspector("检验员王经理");
            plan.setInspectionResult(0); // 未检验
            plan.setIsRejected(0); // 默认
            plan.setCreatedPerson(SecurityUtils.getUsername());
            plans.add(plan);

        }

        // 批量保存检验计划
        for (InspectionPlan plan : plans) {
            inspectionPlanMapper.insertInspectionPlan(plan);
        }
        return AjaxResult.success("成功创建 " + plans.size() + " 条检验计划");
        } catch (Exception e) {
            throw new RuntimeException("创建检验计划失败: " + e.getMessage());
        }
    }

    @Override
    public AjaxResult updateInspectionResult(InspectionPlanVO  inspectionPlanVO) {
        try{
        // 更新检验计划主表
        InspectionPlan plan = new InspectionPlan();
        BeanUtils.copyProperties(inspectionPlanVO, plan);
        plan.setInspectionStatus(2); // 已检验
        inspectionPlanMapper.updateInspectionPlan(plan);

         // 保存不合格记录
        if (inspectionPlanVO.getRejectionRecords() != null && !inspectionPlanVO.getRejectionRecords().isEmpty()) {

            for (RejectionRecord record : inspectionPlanVO.getRejectionRecords()) {
//                rejectionRecordMapper.deleteRejectionRecordByPlanId(plan.getPlanId());
                record.setPlanId(plan.getPlanId());
                rejectionRecordMapper.insertRejectionRecord(record);
            }
        }
        // 保存检验指标结果
        if (inspectionPlanVO.getInspectionResults() != null && !inspectionPlanVO.getInspectionResults().isEmpty()) {

            for (InspectionResult result : inspectionPlanVO.getInspectionResults()) {
                //            inspectionResultMapper.deleteInspectionResultByPlanId(plan.getPlanId());
                result.setPlanId(plan.getPlanId());
                inspectionResultMapper.insertInspectionResult(result);
            }

        }

        // 更新箱码的检验状态和收货状态
        boxCodesMapper.updateInspectionStatusByBatch(plan.getBatch(), 2L);
        materialReceiveMapper.updateReceivingStatusByBatch(plan.getBatch(), 2L);
        return AjaxResult.success("检验数据更新成功");
        } catch (Exception e) {
            throw new RuntimeException("更新检验数据失败: " + e.getMessage());
        }

    }

    @Override
    public AjaxResult updateRejectStatus(Long id, Long rejectStatus) {
        return null;
    }
    /**
     * 查询收料检验计划VO
     *
     * @param id 收料检验计划主键
     * @return 收料检验计划
     */
    @Override
    public InspectionPlanVO selectInspectionPlanVOById(Long id) {
        InspectionPlanVO planVO = inspectionPlanMapper.selectInspectionPlanVOById(id);
        if (planVO != null) {
            // 加载不合格记录
            List<RejectionRecord> rejectionRecords = rejectionRecordMapper.selectRejectionRecordByPlanId(planVO.getPlanId());
            planVO.setRejectionRecords(rejectionRecords);

            // 加载检验指标结果
            List<InspectionResult> inspectionResults = inspectionResultMapper.selectInspectionResultByPlanId(planVO.getPlanId());

            // 加载检验方案和检验项目
            InspectionScheme scheme = inspectionSchemeMapper.selectInspectionSchemeByItemId(planVO.getItemId());
           // 为检验结果加载检验项目信息
            for (InspectionResult result : inspectionResults) {
                InspectionItem item = inspectionSchemeMapper.selectInspectionItemByschemeIdAnditemId(scheme.getSchemeId(), result.getInspectionItemId());
                if (item != null) {
                    result.setItemName(item.getItemName());
                    result.setInspectionIndex(item.getInspectionIndex());
                    result.setInspectionMethod(item.getInspectionMethod());
                    result.setStandardValue(item.getStandardValue());
                    result.setUpperLimit(item.getUpperLimit());
                    result.setLowerLimit(item.getLowerLimit());
                }
            }
            planVO.setInspectionResults(inspectionResults);



            if (scheme != null) {
                List<InspectionItem> inspectionItems = inspectionSchemeMapper.selectInspectionItemList(scheme.getSchemeId());
                planVO.setInspectionScheme(scheme);
                planVO.setInspectionItems(inspectionItems);
            }
        }

        return planVO;

    }


    /**
     * 查询收料检验计划页面VO
     *
     * @param id 收料检验计划主键
     * @return 收料检验计划
     */
    @Override
    public List<InspectionPlanVO> selectInspectionPlanVOList(InspectionPlanVO inspectionPlanVO) {

        List<InspectionPlanVO> planList = inspectionPlanMapper.selectInspectionPlanVOList(inspectionPlanVO);
        // 为每个检验计划加载关联数据
        for (InspectionPlanVO planVO : planList) {
            // 加载不合格记录
            List<RejectionRecord> rejectionRecords = rejectionRecordMapper.selectRejectionRecordByPlanId(planVO.getPlanId());
            planVO.setRejectionRecords(rejectionRecords);

            // 加载检验指标结果
            List<InspectionResult> inspectionResults = inspectionResultMapper.selectInspectionResultByPlanId(planVO.getPlanId());
            // 为检验结果加载检验项目信息

            // 加载检验方案和检验项目
            InspectionScheme scheme = inspectionSchemeMapper.selectInspectionSchemeByItemId(planVO.getItemId());

            for (InspectionResult result : inspectionResults) {
                InspectionItem item = inspectionSchemeMapper.selectInspectionItemByschemeIdAnditemId(scheme.getSchemeId(), result.getInspectionItemId());
                if (item != null) {
                    result.setItemName(item.getItemName());
                    result.setInspectionIndex(item.getInspectionIndex());
                    result.setInspectionMethod(item.getInspectionMethod());
                    result.setStandardValue(item.getStandardValue());
                    result.setUpperLimit(item.getUpperLimit());
                    result.setLowerLimit(item.getLowerLimit());
                }
            }
            planVO.setInspectionResults(inspectionResults);
        }
        return planList;
    }

    /**
     * 查询收料检验计划
     * 
     * @param id 收料检验计划主键
     * @return 收料检验计划
     */
    @Override
    public InspectionPlan selectInspectionPlanById(Long id)
    {
        return inspectionPlanMapper.selectInspectionPlanById(id);
    }

    /**
     * 查询收料检验计划列表
     * 
     * @param inspectionPlan 收料检验计划
     * @return 收料检验计划
     */
    @Override
    public List<InspectionPlan> selectInspectionPlanList(InspectionPlan inspectionPlan)
    {
        return inspectionPlanMapper.selectInspectionPlanList(inspectionPlan);
    }

    /**
     * 新增收料检验计划
     * 
     * @param inspectionPlan 收料检验计划
     * @return 结果
     */
    @Override
    public int insertInspectionPlan(InspectionPlan inspectionPlan)
    {
        return inspectionPlanMapper.insertInspectionPlan(inspectionPlan);
    }

    /**
     * 修改收料检验计划
     * 
     * @param inspectionPlan 收料检验计划
     * @return 结果
     */
    @Override
    public int updateInspectionPlan(InspectionPlan inspectionPlan)
    {
        return inspectionPlanMapper.updateInspectionPlan(inspectionPlan);
    }

    /**
     * 批量删除收料检验计划
     * 
     * @param ids 需要删除的收料检验计划主键
     * @return 结果
     */
    @Override
    public int deleteInspectionPlanByIds(Long[] ids)
    {
        return inspectionPlanMapper.deleteInspectionPlanByIds(ids);
    }

    /**
     * 删除收料检验计划信息
     * 
     * @param id 收料检验计划主键
     * @return 结果
     */
    @Override
    public int deleteInspectionPlanById(Long id)
    {
        return inspectionPlanMapper.deleteInspectionPlanById(id);
    }
}
